<?php
/**
 * Model_InfoCommon
 *
 * @package    model
 */
class Model_MassCommon extends Model_Mine {
	
	static protected $cus_id ;
	static protected $appid ;
	static protected $secret ;
	static protected $configModel ;
	
	static function getToken($cus){
			
		if(!is_int($cus)){return '请先登录';}
		self::$cus_id = $cus;
		
		/* 微信 appid & secret */
		self::$configModel = new Model_CustomerConfig;
		$sql = "select c_value from customer_config where customer_id='".$cus."' and c_type='appid'";
		$info = self::$configModel->fetchRow($sql);

		if(empty($info)){return '请先填写微信授权配置';}
		
		$appinfo = explode(',',$info['c_value']);
		self::$appid	 = $appinfo[0];	
		self::$secret	 = $appinfo[1];
		
		if($_SESSION['WXTOKEN'] && $_SESSION['validTime']>time()){
			return $_SESSION['WXTOKEN'];						//已存在 则直接返回
		}else
		
		if($_SESSION['WXTOKEN'] && $_SESSION['validTime']<time()){
			$_SESSION['WXTOKEN'] = self::anewGetToken();		//已存在 但过期 重新获取
			$_SESSION['validTime'] = time() + 6000;
		}else
		
		if(!$_SESSION['WXTOKEN']){								//session 不存在 从数据库取
		
			if($info['token'] && $info['valid_time']>time()){	//新鲜可用的话直接使用
				$_SESSION['WXTOKEN'] 	= $info['token'];
				$_SESSION['validTime']  = $info['valid_time'];
			}else
			
			if($info['token'] && $info['valid_time']<time()){
				$_SESSION['WXTOKEN']   = self::anewGetToken();	//已存在 但过期 重新获取
				$_SESSION['validTime'] = time() + 6000;
			}else{
				$_SESSION['WXTOKEN']   = self::anewGetToken();	//已存在 但过期 重新获取
				$_SESSION['validTime'] = time() + 6000;
			}
		}
		
		return $_SESSION['WXTOKEN'];
	}
	
	//获取token 并 保存
	static function anewGetToken(){
	
		//获取token
		$getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".self::$appid."&secret=".self::$secret;
		$tokenArray = Model_PostCurl::wx_send($getTokenUrl);
		
		if($token = $tokenArray['access_token']){

			$updata['token'] 	  = $token;
			$updata['valid_time'] = time()+6000;
			
			self::$configModel->row_update($updata,"customer_id='".self::$cus_id."' and c_type='token'");
			return $token;
		}
	}
}

